package com.qiangesoft.ip.util;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * ip转地址工具类
 *
 * @author qiangesoft
 * @date 2024-02-01
 */
public class Ip2regionUtil {

    private static Searcher searcher;

    public static void main(String[] args) {
        String ip2region = getIp2region("171.223.209.192");
        System.out.println(ip2region);
    }

    /**
     * 在服务启动时加载ip2region.db到内存中
     */
    static {
        try {
            InputStream inputStream = Ip2regionUtil.class.getResourceAsStream("/ip2region/ip2region.xdb");
            byte[] byteArray = FileCopyUtils.copyToByteArray(inputStream);
            // 缓存xdb数据
            searcher = Searcher.newWithBuffer(byteArray);
            // 基于文件查询
            // Searcher.newWithFileOnly("/ip2region/ip2region.xdb");
            // 缓存VectorIndex索引
            // Searcher.newWithVectorIndex("/ip2region/ip2region.xdb", null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据ip2region解析ip地址
     *
     * @param ip
     * @return
     */
    public static String getIp2region(String ip) {
        if (searcher == null) {
            return null;
        }

        try {
            return searcher.search(ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

